import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { CometdMtEntity, ListTranslator } from './translator'
import { differenceBy } from 'lodash-es'
import Alert, { Confirm } from '@/components/Alert'
import { useGlobalStore } from '@/store/global'
import { useMccStore } from '../../store'
import { Mt, MtEntity, revert_mt } from '@/api/manager/mt'
import { useManagerStore } from '../main/manager/store'
import { getItemByMtKey, getItemInTree } from '../main/table/all/utils'
import { init as addMtInit, mccAddMt } from '@/components/AddMt/store.trans'
import {
	fetchAddRollCallCallee,
	fetchDelRollcalleeList,
	fetchGetRollInfo,
	fetchGetRollPlanList,
	fetchRemarkSave,
	fetchRollCallCallee,
	fetchRollCallCheck,
	fetchRollCaller,
	fetchRollCancelChairman,
	fetchRollSetChairman,
	fetchRollSetSpeaker,
	fetchSaveRollCallBeforeStar,
	fetchSaveRollcalleeList,
	fetchSearchCallee,
	fetchSetRollcallResult,
	fetchStartRollCall,
	fetchStartSelectView,
	fetchStopRoll,
} from '@/api/manager/roll'
import { callerOptionsEntity, initData, PageEntity, searchSuccessCallParamsEntity } from './interface'
import { MEETING_JUMP_URL } from '@/utils/constant'
import { fetchStopRollCall, fetchUpdatePollState } from '@/api/manager/poll'
import { MccModel } from '../main/table/all/translator'
import { IMcc, makeMtParam } from '@/api/manager/type'
import { useTableAllStore } from '@/pages/manager/blocks/main/table/all/store'
import { fetchStopAllSelectView, fetchStopSelectView } from '@/api/manager/select'
import { FetchRollInfoEntity, SelectViewParamsEntity } from '@/api/manager/roll/interface'
import { some, filter } from 'lodash-es'
import { useMonitorStore } from '../monitor/store'
import { regexEnum } from '@/utils'
import { listOrderClick } from '@/utils/listSlice'

type MeetingType = 0 | 2 | 1 | undefined

type RollStore = PageEntity & {
	/**处理入参params */
	dealParams: (mt: MtEntity) => any
	/**被点名人列表改变时调用此方法 添加、删除、拖动 都需要调用此方法*/
	changeCalleeList: () => void
	addMts: (data: { mtList: Array<MtEntity>; smcumtid?: string }) => void
	saveAddedMts: (mts: Array<MtEntity>, smcumtid: string) => void
	/**去重 */
	arrUnique: (arr: any, mt: any) => boolean
	initGetRollCallInfoCallBack: (_data: FetchRollInfoEntity) => void
	/**清空当前被点名人列表*/
	clearCurRollcallee: () => void
	//设置当前点名人
	setCurRollcallee: (mt: MtEntity | null) => void
	/**获取当前选中终端的mtid */
	pageGetCurRollcallee: () => MtEntity | null
	/**清除缓存清空当前点名人*/
	pageDataClearCurRollcallee: () => void
	/**获取当前点名人*/
	pageDataGetCurRollcallee: () => MtEntity | null
	/**更新 */
	update: (d: Partial<PageEntity & { _start: string; _changes: string[] }>) => void
	/**新增终端 */
	addList: (_list: MtEntity[]) => void
	/**删除终端 */
	delCalleeListBtnClick: () => void
	/**备注点击 */
	remark: () => void
	/**备注关闭*/
	closeRemark: () => void
	/**备注保存*/
	remarkSave: (remark: string) => void
	/**清空 被点名人*/
	clearCalleeListBtnClick: () => void
	clearRollcalleeList: () => void
	/** 初始化点名人下拉列表 */
	initRollCallerList: () => void
	/**删除退会终端 */
	removeLi: (mts: Array<string>) => void
	/**多选删除被点名列表 */
	delRollcalleeList: () => void
	isMtsAddedByRollcall: () => boolean
	/**删除终端 */
	delRollCall: (arr: Array<MtEntity>) => void
	/**判断按钮状态 */
	checkLimits: () => void
	/**点名上一个下一个按钮判断 */
	showOrHideRollcallUpOrNextBtn: () => void
	/**显示和隐藏监控按钮 */
	showOrHideCamerarcBtn: () => void
	/**mcc JS里面更新终端的在离线状态 */
	mccUpdateList: (updateList: MtEntity[]) => void
	updateList: (updateList: MtEntity[]) => void
	/**获取查询参数*/
	// getPara: () => StartParamsMixEntity
	testName: (_name: string) => boolean
	msgHandle: (_data: CometdMtEntity) => void
	/**设置点名结果 */
	setRollcallResult: (mtKey: string, pass_type: 0 | 1) => void
	toggleClick: (mtKey: string) => void
	toggleCtrl: (mtKey: string) => void
	toggleShift: (mtKey: string) => void
	changeSet: (key: string) => void
	resetSearchInput: () => void
	saveStartList: () => void
	callPre: () => void
	callNext: () => void
	/**停止旧点名人选看(画面和成) */
	_handleStopOldRollcallerSelect: (mt: MtEntity) => void
	/**修改混音成员有画面合成会清理画面合成消息（后台操作） */
	_handleChangeMixMember: (mt: MtEntity) => void
	/**修改混音成员有画面合成会清理画面合成消息被点名模式特殊操作需要在混音清除之后设置发言人（被点名模式）*/
	_handleChangeMixMemberBe: (mt: MtEntity) => void
	/**处理改变混音成员的回调 */
	_handleDealSetRoll: (mt: MtEntity) => void
	/**停止旧被点名人选看点名人(画面合成) */
	_handleStopOldRollcalleeSelectRollcaller: (preMt: MtEntity, rollcallee: MtEntity) => void
	/**传递控件下一次点名人消息 */
	_handleNewRollcalleeIntoMonitor: (mt: MtEntity) => void
	sendMess: (rollMode: string, rollcaller?: MtEntity | null, rollcallee?: MtEntity) => void
	/**点名上一个   点名下一个  点名除初始化点名除外 */
	_rollcallMemberSendMess: (mt: MtEntity) => void
	/**展示会场图像 */
	rcShow: () => void
	/**邀请终端 */
	addMt: () => void
	/**切换点名人 */
	changeCaller: (mt_key: string, Item: any) => null | undefined
	/**点名人下拉框展示和关闭*/
	callerPanelToggle: (flag: boolean) => void
	/**打开点名签到表*/
	showSignResult: () => void
	/**禁用点名签到表*/
	disableSignResultBtn: () => void
	/**放开点名签到表 */
	enableSignResultBtn: () => void
	/**修改点名签到表样式*/
	changeSignResultBtn: (flag?: boolean, isOpen?: boolean) => void
	saveRollcalleeList: () => void
	getPlanPara: (isUpdate: boolean) => {
		id: string
		members: {
			account_type: number
			mt_id: string
			account: string
			mt_key: string
			moid: string
			e164: string
			conf_e164: string
		}[] //轮询成员
		name: string // 预案名称
	}
	/**判断是否在进行点名轮询 */
	isRollcallCurrent: () => boolean
	/**把上线的终端添加到点名人select下拉列表中 */
	addMtToRollcallerSelectList: (mt: MtEntity) => void
	addMtToCalleeList: (mt: MtEntity) => void
	/**终端上线/下线通知 */
	mtOnlineStatusChangeNotify: (
		onlineMts: Array<MtEntity>,
		offlineMts: Array<{ mt_key: string }>,
		newAddMts: Array<MtEntity>,
		isDel?: boolean
	) => void
	/**获取是否开启语音激励*/
	isMeetingVoiceInspireOn: () => boolean
	// 根据mtid获取终端
	getMtByMtid: (key: string) => MtEntity | null
	/**判断终端是否在线 */
	isMtOnline: (mt: MtEntity) => boolean
	/**初始化轮询预案 */
	initPollSchema: (name?: string) => void
	/**点名人选看被点名人 */
	rollcallerSelectViewRollcallee: (dstAccount: MtEntity | null, srcAccount: MtEntity, Bus?: boolean) => void
	/**开始点名 6.0做限制,点名会议轮询不能同时打开*/
	checkRollAll: () => void
	setRollcaller: (rollcaller: MtEntity | null) => void
	/**发送点名轮询接口 */
	startPost: () => void
	/**设置当前点名轮询的状态 */
	setRollcallState: () => void
	/**开始点名回调*/
	startPostCallback: () => void
	/**开启点名轮询后成功的回调（渲染界面） */
	startRollcall: () => void
	/**检测是不是所有的被点名人都不在线 */
	_isAllRollcalleesOffline: () => boolean
	/**拿到被点名列表中第一个被点名终端 */
	getFirstRollcalleeInList: () => MtEntity | null
	_rollCallTheFirstInList: (mt: MtEntity | null) => void
	/**开始点名轮询*/
	startBtnClick: () => void
	/**停止点名轮询*/
	stopRollClick: () => void
	/**恢复停止点名的样式 */
	stopRollcall: () => void
	/**获取当前点名人信息*/
	getCurRollCaller: () => MtEntity | null
	/**找到当前被点名人列表在点名列表当中位置(如果是-1证明找不到)*/
	getLiDom: (key: string) => number
	/**获取当前点名终端的上一个/下一个 可被点名的终端（如何获取以需求而定） */
	getRollcallee: (upOrDown: number, isCheck?: boolean) => null | MtEntity
	moveThroughList: (upOrDown: number, curMt?: MtEntity | null, isCheck?: boolean) => null | MtEntity
	/**终端的单个删除 */
	removeClick: (mt: MtEntity) => void
	/**删除终端 */
	delMt: (mt: MtEntity) => void
	/**删除被点名人列表中的终端 */
	delRollcallee: (mt: MtEntity) => void
	/**在点名人列表中标记出下线的终端，下次下拉时清除下线的终端 */
	markOfflineMtInRollcallerList: (mt: { mt_key: string }) => void
	/**获取当前被点名人列表中是否有点名人 */
	hasRollcallees: () => boolean
	/**获取当前管理方 */
	_getCurChairman: () => null | MtEntity
	/**获取当前发言人 */
	_getCurSpeaker: () => null | MtEntity
	/**设置管理方 */
	setMtToChairman: (mt: MtEntity, callback?: () => void) => void
	/**取消管理方 */
	cancelChairman: () => void
	/**设置发言人 */
	setMtToSpeaker: (mt: MtEntity | null, callback?: () => void) => void
	/**检测当前点名环境*/
	_handleCheckRollCallEnvironment: (mt: MtEntity) => boolean
	/** */
	checkMtCanBeRollCall: (mt: MtEntity) => string
	/**检测本次点名是否OK */
	checkRollcallOK: (mt: MtEntity) => string
	/**检测被点名人 */
	_checkMtCanBeRollcall: (mt: MtEntity | null) => string
	/**检测点名人是否出现在被点名列表当中 */
	_checkCanChangeRollcaller: () => boolean
	/**对终端点名 */
	rollCallMember: (mt: MtEntity, keepLasttimeResult: any) => void
	/**调用接口 */
	controllerRollCall: (mt: MtEntity, callback?: () => void) => void
	/**搜索成功的回调函数 */
	searchSuccessCall: (_data: searchSuccessCallParamsEntity) => void
	/**搜索过程中添加人员 */
	addMtsIndrop: (mts: Array<MtEntity>, successCallbackFn: (params: searchSuccessCallParamsEntity) => void) => void
	/**渲染被选看列表 */
	renderRollCalleeList: (mts: Array<MtEntity>) => void
	/**为被点名人添加点名状态 更改List状态 */
	addUserState: () => void
	/**被点名的的点名状态，1 点名通过； 0 点名未通过；2 未被点过名。 */
	getStatePass: (mtKey: string, calleePass: Array<MtEntity>, calleeNoPass: Array<MtEntity>) => number
	/**选中终端 */
	setMtSelected: (mt?: MtEntity) => void
	/**按下键盘搜索 */
	searchInputKeyup: (val: string) => void
	/**按下键盘搜索处理方法 */
	doSearch: (key: string) => void
	/**在搜索中拖拽添加终端 */
	dropMtInSearch: (_data: Array<Mt>) => void
	/**发送新增接口 */
	sendAddMtsAjax: (_data: Array<Mt>) => void
	/**重置搜索相关内容*/
	resetSearch: () => void
	/**调用搜索接口 获取搜索结果 */
	getSearchResult: (text: string, successCallbackFn: (params: searchSuccessCallParamsEntity) => void) => void
	/**获取点名信息 */
	getInfo: (callback: (_res: FetchRollInfoEntity) => void) => void
	/**切换点名模式*/
	changeMode: (value: string) => void
	/**点名未开启下操作点名人、模式、预案，保存到后端 */
	saveRollCallBeforeStart: () => void
}
export const store = createVanilla<RollStore>((set, get) => ({
	...initData,
	update: (d) => set({ ...d }),
	getInfo: async (successCallbackFn) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchGetRollInfo(meetingMoid)
		if (res.success && res.data) {
			successCallbackFn(res.data)
		} else {
			// window.TS.monitor?.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			Alert(res.description || t('操作失败'))
		}
	},
	dealParams: (MT) => {
		return {
			portrait: MT.portrait,
			account: MT.account || '' /**必须 */,
			account_type: MT.account_type /**必须 */,
			conf_e164: MT.conf_e164 ?? '' /**必须 */,
			e164: MT.e164 ?? '' /**必须 */,
			mt_key: MT.mt_key ?? '' /**必须 */,
			mt_type: MT.mt_type /**必须 */,
			mt_id: MT.mt_id ?? MT.mt_key ?? '' /**必须 */,
			name: MT.name ?? '' /**必须 */,
			online: MT.online ?? 0 /**必须 */,
			stream: MT.stream ?? 0 /**必须 */,
		}
	},
	/**清空当前被点名人*/
	clearCurRollcallee: () => {
		set({ cur_roll_callee: null })
	},
	setCurRollcallee: (mt) => {
		if (mt != null && mt.mt_key) {
			set({ cur_roll_callee: mt })
		}
		get().showOrHideRollcallUpOrNextBtn()
	},
	getFirstRollcalleeInList: () => {
		let mt = get().list[0]
		return mt ? revert_mt(mt.mcc) : null
	},
	pageGetCurRollcallee: function () {
		let result = get().list.find((item) => {
			return item.status.checked
		})
		if (result) {
			return revert_mt(result.mcc)
		}
		return null
	},
	changeMode: async (value) => {
		const { saveRollCallBeforeStart } = get()
		set({ modeValue: value })
		saveRollCallBeforeStart()
	},
	saveRollCallBeforeStart: async () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { planOptions, planValue, modeValue, callerValue, getCurRollCaller } = get()
		const item = planOptions.find((item) => item.value === planValue)
		let params = { mode: modeValue, name: item?.label || t('不使用预案') }
		if (callerValue !== '-1' /**当前点名人存在*/) {
			params = Object.assign({}, params, {
				roll_caller: getCurRollCaller(),
			})
		}
		let res = await fetchSaveRollCallBeforeStar(meetingMoid, params)
		!res.success && Alert(res.description || '')
	},
	getCurRollCaller: () => {
		const { callerValue } = get()
		const tableAll = useTableAllStore.getState().tree
		if (callerValue !== '-1') {
			let mtInfo: MccModel<IMcc> | null = getItemByMtKey(tableAll, callerValue)
			if (mtInfo !== null && mtInfo.mcc.isMt) {
				return revert_mt(mtInfo.mcc)
			}
		}
		return null
	},
	checkRollcallOK: (cur_roll_callee) => {
		const _cur_roll_caller = get().getCurRollCaller()
		if (!_cur_roll_caller) {
			return t('请设置点名人')
		}
		// 点名人不在线
		if (!_cur_roll_caller || _cur_roll_caller.online != 1) {
			return t('点名人不在线')
		}
		// 检测被点名人
		return get()._checkMtCanBeRollcall(cur_roll_callee)
	},
	_checkCanChangeRollcaller: () => {
		const { list, getCurRollCaller } = get()
		const _cur_roll_caller_key = getCurRollCaller()?.mt_key ?? ''
		const flag = list.some((item) => {
			return item.mtKey === _cur_roll_caller_key
		})
		return flag
	},
	_checkMtCanBeRollcall: (cur_roll_callee) => {
		const _cur_roll_caller = get().getCurRollCaller()
		if (!_cur_roll_caller) {
			return t('请设置点名人')
		}
		// 点名人不在线
		if (!_cur_roll_caller || _cur_roll_caller.online != 1) {
			return t('点名人不在线')
		}
		// 检测点名人和被点名人
		if (_cur_roll_caller.mt_key === cur_roll_callee?.mt_key) {
			return t('点名人和被点名人不能为同一个人')
		}
		// 被点名终端不在线时
		if (!cur_roll_callee?.online) {
			return t('被点名人不在线')
		}
		return 'ok'
	},
	rollCallMember: (rollCallee) => {
		const {
			state,
			isMeetingVoiceInspireOn,
			checkRollcallOK,
			controllerRollCall,
			setMtSelected,
			enableSignResultBtn,
			getRollcallee,
			sendMess,
			modeValue,
			getCurRollCaller,
			setCurRollcallee,
		} = get()
		if (!state) {
			return false
		}
		if (isMeetingVoiceInspireOn()) {
			Alert(t('定制混音和语音激励不能同时开启'))
			return false
		}
		// 检测本次点名是否OK
		var result = checkRollcallOK(rollCallee)
		if (result !== 'ok') {
			Alert(result)
			return
		}
		sendMess(modeValue, getCurRollCaller(), rollCallee) //发送顺序消息
		let callBack = function () {
			setMtSelected(rollCallee)
			enableSignResultBtn() //启用签到表按钮
			setCurRollcallee(rollCallee)
			//切换控件
			let nextcurCallee = getRollcallee(1, true)
			if (!state) {
				// TS.monitor.dialog.show()
				useMonitorStore.getState().showRollCallDialog()
			} else {
				if (nextcurCallee) {
					// TS.monitor.dialog.show(rollCallee, nextcurCallee)
					useMonitorStore.getState().showRollCallDialog(rollCallee, nextcurCallee)
				} else {
					// TS.monitor.dialog.show(rollCallee, null)
					useMonitorStore.getState().showRollCallDialog(rollCallee)
				}
			}
			set({ openShow: true })
		}
		setTimeout(() => {
			controllerRollCall(rollCallee, callBack)
		}, 230)
	},
	/**点名终端 */
	controllerRollCall: async (rollcallee, callback) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const _cur_roll_caller = get().getCurRollCaller()
		const { modeValue, setRollcallResult } = get()
		let res: any = await fetchRollCaller(meetingMoid, {
			mode: +modeValue,
			roll_callee: rollcallee,
			roll_caller: _cur_roll_caller ?? null,
		})
		if (res.success) {
			callback && callback()
		} else {
			if (res.data === 'ROLLCALL_MIX_FAIL' /**定制混音失败 */) {
				setRollcallResult(rollcallee.mt_key, 0)
				Alert(t('点名失败（无法开启定制混音）'))
			} else {
				Alert(res.description || t('操作失败'))
			}
		}
	},
	testName: (name) => {
		if (
			!name ||
			!regexEnum.testCharacter.test(name) ||
			!regexEnum.testSpecial.test(name) ||
			!regexEnum.testLength.test(name)
		)
			return true
		return false
	},
	/**新增终端*/
	addList: (addList) => {
		const { list } = get()
		const mt = get().getCurRollCaller()
		let result = addList.filter((item) => {
			return item.mt_key != mt?.mt_key
		})
		let mts = ListTranslator(result)
		const insertList = differenceBy(mts, list, (x) => x.mtKey)
		set({
			list: [...list.slice(0, list.length), ...insertList, ...list.slice(list.length)],
		})
	},
	_getCurChairman: () => {
		let chairman = useManagerStore.getState().chairman
		return chairman ? revert_mt(chairman) : null
	},
	_getCurSpeaker: function () {
		let speaker = useManagerStore.getState().speaker
		return speaker ? revert_mt(speaker as Mt) : null
	},
	setMtToChairman: (mt: MtEntity, callBack) => {
		var cMt = get()._getCurChairman()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (mt.mt_key != cMt?.mt_key) {
			fetchRollSetChairman(meetingMoid, mt)
			callBack && callBack()
		} else {
			callBack && callBack()
		}
	},
	cancelChairman: () => {
		var cMt = get()._getCurChairman()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (cMt && cMt.mt_key) {
			fetchRollCancelChairman(meetingMoid, cMt)
		}
	},
	setMtToSpeaker: async (mt, callBack) => {
		let speaker_mt_key = get()._getCurSpeaker()?.mt_key ?? ''
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (mt?.mt_key != speaker_mt_key) {
			const res: any = await fetchRollSetSpeaker(meetingMoid, mt)
			if (!res.success) {
				// NACK 处理逻辑
				// if (res.data == 'NACK_ERROR_CODE') {
				// 	var message = res.description
				// 	if (message.match('xxx')) {
				// 		// 若需要弹出的消息中包含'xxx',替换成终端的名字
				// 		var mtName = mt?.name
				// 		message = message.replace(/xxx/, mtName)
				// 	}
				// }
				callBack && callBack()
			} else {
				callBack && callBack()
			}
		} else {
			callBack && callBack()
		}
	},
	remark: () => {
		let checkedList = get().list.filter((x) => x.status.checked) /**选中的终端*/
		if (checkedList.length === 0) {
			Alert(t('请先选择终端'))
			return
		} else if (checkedList.length === 1) {
			let result = get().list.map((item) => {
				if (item.status.checked) {
					item.status.remarkTrue = true
				} else {
					item.status.remarkTrue = false
				}
				return item
			})
			set({ list: result })
		} else if (checkedList.length > 1) {
			Alert(t('请单独选择一个点名与会方进行备注'))
			return
		}
	},
	closeRemark: () => {
		// 将所有的备注全部关闭
		let result = get().list.map((item) => {
			item.status.remarkTrue = false
			return item
		})
		set({ list: result })
	},
	remarkSave: async (remark) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let checkedList = get().list.filter((x) => x.status.checked)[0]
		if (checkedList) {
			let _roll_callee = revert_mt(checkedList.mcc)
			const res = await fetchRemarkSave(meetingMoid, { remark: remark, roll_callee: _roll_callee })
			if (res.success) {
				let result = get().list.map((item) => {
					item.status.remarkTrue = false
					if (item.mtKey === _roll_callee.mt_key) {
						item.remark = remark
					}
					return item
				})
				set({ list: result })
			} else {
				Alert(res.description ?? t('操作失败'))
			}
		}
	},
	/**移除终端*/
	delCalleeListBtnClick: () => {
		const { delRollcalleeList, list, state } = get()
		const checkList = list.filter((l) => l.status.checked)
		if (checkList.length <= 0) {
			Alert(t('请先选择终端'))
			return
		}
		if (state) {
			Confirm(t('点名签到表中对应的成员信息也将同步删除，确定继续？'), () => {
				delRollcalleeList()
			})
		} else {
			delRollcalleeList()
		}
	},
	clearCalleeListBtnClick: () => {
		const { isSearch, state, clearRollcalleeList } = get()
		if (isSearch) {
			return
		}
		if (state) {
			Confirm(t('此操作将导致点名签到表成员列表也被清空，确定继续？'), () => {
				clearRollcalleeList()
			})
		} else {
			clearRollcalleeList()
		}
	},
	/** 初始化点名人下拉列表 */
	initRollCallerList: () => {
		/**获取是否有点名人列表 无则初始化为请选择点名人项*/
		let rollCallers: Mt[] = []
		const tableAll = useTableAllStore.getState().tree
		const _tree = getItemByMtKey(tableAll, '0.0.0.0_0')
		const superMtNum = useMccStore.getState().mccInfo.superMtNum
		if (_tree) {
			for (let i = 0; i < _tree.children.length; i++) {
				let { mcc: item } = _tree.children[i]
				if (superMtNum /**超大方会议使用 */) {
					if (
						item.isMt &&
						item.confLevel === 2 &&
						item.mtType !== 3 &&
						item.status.isOnline &&
						item.status.isInteractive
					) {
						rollCallers.push(item)
					}
				} else {
					if (item.isMt && item.confLevel == 2 && item.mtType != 3 && item.status.isOnline) {
						rollCallers.push(item)
					}
				}
			}
		}
		let _result = rollCallers.map((item) => {
			return { name: item.name, mtKey: item.mtKey }
		})
		set({ callerOptions: [{ name: t('请选择点名人'), mtKey: '-1' }].concat(_result) })
	},
	changeCalleeList: () => {
		const { list: mts, checkLimits, saveRollcalleeList, changeSignResultBtn } = get()
		if (mts.length > 5000) {
			Alert(t('参与点名与会方最多为5000方'))
			return
		}
		saveRollcalleeList() //保存列表
		checkLimits() //重置右侧按钮
		changeSignResultBtn()
	},
	addMts: (data: { mtList: Array<MtEntity>; smcumtid?: string }) => {
		const {
			list,
			addMtFlag,
			isSearch,
			searchCacheMt,
			saveAddedMts,
			rollcalleeAccount,
			resetSearch,
			doSearch,
			changeCalleeList,
		} = get()
		let mts = data.mtList
		let smcumtid = data.smcumtid || '0.0.0.0_0' //级联时有值  非级联为0
		let _searchCacheMt = []
		let _list = []
		if (list && useMccStore.getState().curPage === 'rollcall') {
			if (list.length + mts.length > 5000) {
				Alert(t('参与点名与会方最多为5000方'))
				return
			}
		}
		const tableAll = useTableAllStore.getState().tree
		function xxx(key: number): MtEntity | null {
			let mt = null
			getItemInTree(tableAll, ({ mcc: item, children }) => {
				if (!item.isMt) {
					let mm = children.find((x) => x.mcc.account == mts[key].account)
					if (mm && item.smcuMtid == smcumtid && mm.mcc.isMt) {
						mt = revert_mt(mm.mcc)
					}
				}
			})
			return mt
		}
		//增加判断添加的终端是否为终端列表中已存在终端的逻辑  加入会议级别
		for (var i = 0; i < mts.length; i++) {
			let j: MtEntity | null
			j = xxx(i)
			let flag = true
			if (j != null) {
				for (var ac = 0; ac < rollcalleeAccount.length; ac++) {
					if (j != null && j.account == rollcalleeAccount[ac].account) {
						let parent_smcuMtid = ''
						getItemInTree(tableAll, ({ mcc: item, children }) => {
							if (!item.isMt) {
								let mm = children.find((x) => x.mtKey == rollcalleeAccount[ac].mt_id)
								if (mm) {
									parent_smcuMtid = item.smcuMtid
								}
							}
						})
						if (smcumtid == parent_smcuMtid) {
							//是同一会议下面的
							flag = false
							break
						}
						if (+smcumtid == 0) {
							flag = false
							break
						}
					}
				}
				if (flag && addMtFlag) {
					if (isSearch) {
						_searchCacheMt.push(j)
						resetSearch()
						doSearch('')
						set({ searchCacheMt: [...searchCacheMt, ..._searchCacheMt] })
					} else if (searchCacheMt.length) {
						_searchCacheMt.push(j)
						set({ searchCacheMt: [...searchCacheMt, ..._searchCacheMt] })
					} else {
						_list.push(ListTranslator([j]))
						set({ list: [...list, ..._list[0]] })
						changeCalleeList()
					}
				}
				mts.splice(i, 1)
				i--
			}
		}
		if (addMtFlag) {
			saveAddedMts(mts, smcumtid)
		}
	},
	saveAddedMts: (mts, smcumtid) => {
		const { rollcalleeAccount, thisMts, arrUnique } = get()
		// 把终端添加到点名轮询的页面缓存中
		// 添加之前判断右边列表是否存在相同终端。
		var isAdd = true
		const tableAll = useTableAllStore.getState().tree
		for (var sMt = 0; sMt < mts.length; sMt++) {
			isAdd = true
			for (var ac = 0; ac < rollcalleeAccount.length; ac++) {
				if (mts[sMt].account == rollcalleeAccount[ac].account) {
					//存在同样的e164号
					if (!rollcalleeAccount[ac].mt_id) continue
					if (smcumtid) {
						//级联会议
						let parent_smcuMtid = ''
						// eslint-disable-next-line no-loop-func
						getItemInTree(tableAll, ({ mcc: item, children }) => {
							if (!item.isMt) {
								let mm = children.find((x) => x.mtKey == rollcalleeAccount[ac].mt_id)
								if (mm) {
									parent_smcuMtid = item.smcuMtid
								}
							}
						})
						if (smcumtid == parent_smcuMtid) {
							//是添加到已有会议中
							isAdd = false
							break
						}
					} else {
						isAdd = false
						break
					}
				}
			}
			if (isAdd && arrUnique(thisMts, mts[sMt])) {
				thisMts.push(mts[sMt])
			}
		}
		thisMts.filter(function (mt) {
			//如果添加的全为已存在终端，则addMtFlag为false
			return mt != null
		})
		set({ thisMts: thisMts })
		if (thisMts.length === 0) {
			set({ addMtFlag: false })
		}
		set({ rollcalleeAccount: [] })
	},
	arrUnique: function (arr, mt) {
		//去重
		var flag = true
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] && arr[i].account == mt.account) {
				flag = false
				break
			}
		}
		return flag
	},
	initGetRollCallInfoCallBack: (_data: FetchRollInfoEntity) => {
		const {
			initPollSchema,
			setRollcallState,
			setRollcaller,
			addUserState,
			enableSignResultBtn,
			changeSignResultBtn,
			checkLimits,
			setCurRollcallee,
			setMtSelected,
			getRollcallee,
			renderRollCalleeList,
		} = get()
		initPollSchema()
		set({
			preName: _data.name ?? '',
			state: _data.state ?? 0,
			roll_call_sign_enable: _data.roll_call_sign_enable,
			modeValue: _data.mode + '',
			roll_callee_pass: _data.roll_callee_pass,
			roll_callee_no_pass: _data.roll_callee_no_pass,
		})
		setRollcallState()
		setRollcaller(_data.cur_roll_caller) /**设置点名人 */
		renderRollCalleeList(_data.roll_callee || []) /**渲染列表*/
		addUserState() /**渲染被点名人列表(初始化点名状态) */
		if (_data.roll_callee.length > 0 && _data.cur_roll_callee && _data.cur_roll_callee.mt_key) {
			enableSignResultBtn() /**点名签到表*/
			if (_data.state === 1) {
				setCurRollcallee(_data.cur_roll_callee)
				setMtSelected(_data.cur_roll_callee) //渲染页面，设置被点名人
				let nextcurCallee = getRollcallee(1, true) ?? null // 获取下一个点名人
				useMonitorStore.getState().showRollCallDialog(_data.cur_roll_callee, nextcurCallee ?? undefined)
				set({ openShow: true }) /**打开眼睛*/
			}
		}
		changeSignResultBtn(true, !!_data.roll_call_sign_enable)
		checkLimits()
	},
	clearRollcalleeList: () => {
		const { checkLimits, openShow, disableSignResultBtn, saveRollcalleeList } = get()
		if (openShow) {
			useMonitorStore.getState().closeRollCall()
			set({ openShow: false })
		}
		set({ list: [] })
		disableSignResultBtn()
		checkLimits()
		saveRollcalleeList()
	},
	saveRollcalleeList: async () => {
		const { list } = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const result = list.map((item) => makeMtParam(item.mcc))
		const res = await fetchSaveRollcalleeList(meetingMoid, result)
		if (res.success) {
		} else {
			// window.TS.monitor?.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			Alert(res.description || t('操作失败'))
		}
	},
	disableSignResultBtn: () => {
		if (!get().state) {
			return
		}
		set({ roll_call_sign_enable_disabled: true })
	},
	enableSignResultBtn: () => {
		if (!get().state) {
			return
		}
		set({ roll_call_sign_enable_disabled: false })
	},
	changeSignResultBtn: (flag, isOpen) => {
		let callee = get().list /**被点名人 */
		let _state = get().state /**点名状态 */
		if (!_state) {
			if (!flag) return
			set({ roll_call_sign_enable_disabled: !isOpen })
		} else {
			set({ roll_call_sign_enable_disabled: callee.length === 0 })
		}
	},
	/**切换点名人 */
	changeCaller: (mt_key: string, Item: callerOptionsEntity) => {
		const {
			_checkCanChangeRollcaller,
			state,
			saveRollCallBeforeStart,
			clearCurRollcallee,
			pageGetCurRollcallee,
			getCurRollCaller,
			_rollCallTheFirstInList,
			callerValue,
			getFirstRollcalleeInList,
		} = get()
		let preCallerValue = callerValue /**上一次点名人*/
		set({ callerValue: mt_key })
		const flag = _checkCanChangeRollcaller() // 检测是否可以切换点名人
		if (flag) {
			Alert(t('点名人{{name}}存在于被点名人列表，请选择其他点名人', { name: Item.name }))
			set({ callerValue: preCallerValue })
			return null
		}
		if (!state) {
			saveRollCallBeforeStart()
			return null
		}
		clearCurRollcallee()
		if (null == Item || Item.mtKey == null) {
			return null
		}
		var rollcallee = pageGetCurRollcallee()
		set({ pre_roll_caller: getCurRollCaller() })
		try {
			_rollCallTheFirstInList(rollcallee)
		} catch (e) {
			if (getCurRollCaller() !== undefined) {
				try {
					let mt = getFirstRollcalleeInList() //拿到第一个
					_rollCallTheFirstInList(mt)
				} catch (e) {
					Alert('当前被点名人列表中没有可以被点名的与会方')
					return
				}
			} else {
				Alert('当前被点名人列表中没有可以被点名的与会方')
				return
			}
		}
		return null
	},
	callerPanelToggle: (flag) => {
		const { initRollCallerList } = get()
		initRollCallerList()
	},
	addMt: function () {
		addMtInit({
			maxRate: useMccStore.getState().mccInfo.meetingRate,
			isSuperMeeting: useMccStore.getState().mccInfo.superMtNum ? true : false,
			curTemplateE164: useMccStore.getState().mccInfo.e164 || '',
			meetingType: useMccStore.getState().mccInfo.meetingType,
			isSupportRtc: !!useMccStore.getState().mccInfo.enableRtc,
			isMcc: true,
			meetingMoid: useMccStore.getState().mccInfo.meetingMoid,
			mccModel: useTableAllStore.getState().tree ?? {},
			smartCascadeMode: useMccStore.getState().mccInfo.smartCascadeMode,
			isOpen: true,
			selectedEntityMts: [],
			onSubmit: ({ selectedList, smcuMtid }) => {
				mccAddMt(selectedList, smcuMtid)
				// if ($('.mcc-monitor-btn').length > 0) {
				// 	//显示会议监控弹窗
				// 	if ($('.mcc-monitor-btn').hasClass('open')) {
				// 		TS.mcc.monitor.controller.showObj()
				// 	}
				// }
			},
		})
		set({ addMtFlag: true })
		get().getInfo(function (data) {
			set({ rollcalleeAccount: data.roll_callee })
		})
	},
	/**删除退会终端 */
	removeLi: (mts) => {
		if (useMccStore.getState().curPage === 'rollcall') {
			const { changeSignResultBtn, list, checkLimits } = get()
			const unRemove = list.filter((l) => !mts.includes(l.mtKey))
			set({ list: unRemove })
			changeSignResultBtn()
			checkLimits()
		}
	},
	_handleCheckRollCallEnvironment: (rollcallee: MtEntity) => {
		const { state, isMeetingVoiceInspireOn, checkMtCanBeRollCall } = get()
		if (!state) {
			return false
		}
		if (isMeetingVoiceInspireOn()) {
			Alert(t('定制混音和语音激励不能同时开启'))
			return false
		}
		const flag = checkMtCanBeRollCall(rollcallee) // 检测定名人和被点名人状态
		if ('ok' !== flag) {
			return false
		}
		return true
	},
	delRollcalleeList: () => {
		const result = get()
			.list.filter((l) => l.status.checked)
			.map((item) => revert_mt(item.mcc))
		const unCheckedCalleeList = get().list.filter((l) => !l.status.checked)
		get().delRollCall(result)
		set({ list: unCheckedCalleeList })
	},
	isMtsAddedByRollcall: () => {
		return get().addMtFlag
	},
	delRollCall: async (_data) => {
		const { changeSignResultBtn, checkLimits } = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchDelRollcalleeList(meetingMoid, _data)
		if (res.success) {
			changeSignResultBtn()
			checkLimits()
		} else {
			// TS.monitor?.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			Alert(res.description || t('操作失败'))
		}
	},
	/**检查右侧按钮状态 */
	checkLimits: () => {
		const { isSearch, list, showOrHideRollcallUpOrNextBtn, showOrHideCamerarcBtn } = get()
		if (isSearch) {
			set({
				disabledCallNext: true,
				disabledDown: true,
				disabledUp: true,
				disabledCallPre: true,
			})
			return false
		}
		let len = list.length
		let select_callee_index_arr: Array<number> = []
		list.forEach((item, index) => {
			if (item.status.checked) {
				select_callee_index_arr.push(index)
			}
		})
		let _first = select_callee_index_arr[0] - 1 /**第一个被选中被点名人索引 */
		let _last = select_callee_index_arr[select_callee_index_arr.length - 1] + 1 /**最后一个被选中被点名人索引 */
		if (0 <= _first && _first <= len - 1) {
			set({ disabledUp: false })
		} else {
			set({ disabledUp: true })
		}
		if (0 <= _last && _last <= len - 1) {
			set({ disabledDown: false })
		} else {
			set({ disabledDown: true })
		}
		showOrHideRollcallUpOrNextBtn()
		showOrHideCamerarcBtn()
	},
	showOrHideRollcallUpOrNextBtn: () => {
		const { cur_roll_callee: _cur_roll_callee, state, list } = get()
		if (_cur_roll_callee && _cur_roll_callee.mt_key) {
			/**获取当前点名人的位置*/
			let _index = list.findIndex(
				(item) => _cur_roll_callee.mt_key === item.mtKey
			) /**找到当前被点名人列表在点名列表当中位置*/
			let len = list.length // 获取点名人数量
			let pre_index = _index - 1 // 上一个点名人索引,此索引需要大于等于0
			let next_index = _index + 1 // 下一个点名人索引,此索引需要小于等于len-1
			console.log(pre_index, next_index)
			if (!(0 <= pre_index && pre_index <= len - 1)) {
				set({ disabledCallPre: true })
			} else {
				if (state) {
					//点名轮询开启并且有正在被点名人时
					set({ disabledCallPre: false })
				}
			}
			if (!(0 <= next_index && next_index <= len - 1)) {
				//选中的是最后一个元素
				set({ disabledCallNext: true })
			} else {
				if (state) {
					set({ disabledCallNext: false })
				}
			}
		} else {
			set({ disabledCallPre: true, disabledCallNext: true })
		}
	},
	showOrHideCamerarcBtn: () => {
		// 无需写此方法
	},
	/**删除被点名人*/
	/**更新终端*/
	updateList: (updateList = []) => {
		let _updates = updateList.filter((mt) => mt.conf_level === 2)
		const newList = get().list
		for (const mt of _updates) {
			for (const item of newList) {
				if (item.mtKey === mt.mt_key) {
					item.mcc = new Mt(mt)
				}
			}
		}
		set({ list: [...newList] })
	},
	mccUpdateList: (updateList = []) => {
		let _list = get().list
		/**离线终端 */
		const offLineList = updateList
			.filter((item) => {
				return !item.online
			})
			.map((l) => l.mt_key)
		/**在线终端*/
		const onLineListNotMtType8Or7 = updateList
			.filter((item) => {
				return item.online && item.mt_type !== 7 && item.mt_type !== 8
			})
			.map((l) => l.mt_key)
		_list = _list.map((item) => {
			if (offLineList.includes(item.mtKey)) {
				item.status.isOnline = false
				item.mcc.status.isOnline = false
			}
			if (onLineListNotMtType8Or7.includes(item.mtKey)) {
				item.status.isOnline = true
				item.mcc.status.isOnline = true
			}
			return item
		})
		/**删除终端 */
		const onLineListISMtType8Or7 = updateList.filter((item) => {
			return item.online && !(item.mt_type !== 7 && item.mt_type !== 8)
		})
		const onLineListISMtType8Or7Key = updateList
			.filter((item) => {
				return item.online && !(item.mt_type !== 7 && item.mt_type !== 8)
			})
			.map((l) => l.mt_key)
		if (useMccStore.getState().curPage === 'rollcall') {
			if (onLineListISMtType8Or7.length !== 0) {
				get().delRollCall(onLineListISMtType8Or7)
				_list = _list.filter((item) => {
					return !onLineListISMtType8Or7Key.includes(item.mtKey)
				})
			}
		}
		set({ list: _list })
	},
	msgHandle: (_data: CometdMtEntity) => {
		const source = _data.data
		if (!(source.state === 0)) {
			set({ list: [] })
		}
	},
	setRollcallResult: async (mtKey, pass_type) => {
		let operate_item = get().list.find((item) => mtKey === item.mtKey)
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (operate_item) {
			const cur = revert_mt(operate_item.mcc)
			const res = await fetchSetRollcallResult(meetingMoid, {
				pass_type: pass_type,
				roll_callee: cur,
			})
			if (res.success) {
				let result = get().list.map((item) => {
					if (item.mtKey === mtKey) {
						item.status.pass = pass_type
					}
					return item
				})
				set({ list: result })
			} else {
				// window.TS.monitor?.dialog.hide()
				useMonitorStore.getState().closeRollCall()
				Alert(res.description || t('操作失败'))
			}
		}
	},
	toggleClick: (mtKey) => {
		const { list, checkLimits } = get()
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = true
				if (item.status.remarkTrue) {
					return
				}
			} else {
				item.status.checked = false
				item.status.remarkTrue = false
			}
		})
		set({ list: [...list], _start: mtKey, _changes: [] })
		checkLimits()
	},
	toggleCtrl: (mtKey) => {
		const { list, checkLimits } = get()

		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = !item.status.checked
				if (item.status.remarkTrue) {
					return
				}
			} else {
				item.status.remarkTrue = false
			}
		})
		set({ list: [...list], _start: mtKey, _changes: [] })
		checkLimits()
	},
	toggleShift: (mtKey) => {
		const { list, _changes, _start, checkLimits } = get()
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				if (item.status.remarkTrue) {
					return
				}
			} else {
				item.status.remarkTrue = false
			}
		})
		if (_changes.length > 0) {
			for (const item of list) {
				if (_changes.includes(item.mtKey)) {
					item.status.checked = false
				}
			}
		}
		let newChanges = []
		let startItem = list.find((x) => x.mtKey === _start)
		if (startItem) {
			if (startItem?.mtKey === mtKey) {
				startItem.status.checked = true
				newChanges.push(startItem?.mtKey)
			} else {
				let _flag = false,
					_time = 0
				for (const item of list) {
					if (item.mtKey === mtKey || item.mtKey === _start) {
						item.status.checked = true
						newChanges.push(item.mtKey)
						_flag = ++_time === 1
					}
					if (_flag) {
						item.status.checked = true
						newChanges.push(item.mtKey)
					}
				}
			}
		}
		set({ list: [...list], _changes: newChanges })
		checkLimits()
	},
	/**
	 *
	 * @param isUpdate 是否是更新预案
	 * @returns
	 */
	getPlanPara: (isUpdate: boolean) => {
		const { list, preName, name, planValue } = get()
		const _members = list.map((item) => {
			const data = item.mcc
			return {
				account_type: Number(data.accountType ? data.accountType : 0),
				mt_id: data.mtid ? data.mtid : '',
				account: data.account ? data.account : '',
				mt_key: data.mtKey ? data.mtKey : '',
				moid: data.moid ? data.moid : '',
				e164: data.e164 ? data.e164 : '',
				conf_e164: data.confE164 ? data.confE164 : '',
			}
		})
		const _name = isUpdate ? preName : name
		const _id = isUpdate ? planValue : ''
		return {
			id: _id,
			members: _members, //轮询成员
			name: _name, // 预案名称
		}
	},
	changeSet: (key: string) => {
		const { closeRemark, changeCalleeList, disabledDown, disabledUp } = get()
		if (
			(key === 'down' && disabledDown) ||
			(key === 'up' && disabledUp) ||
			(key === 'top' && disabledUp) ||
			(key === 'bottom' && disabledDown)
		) {
			return
		}
		closeRemark()
		if (key === 'top' || key === 'up' || key === 'down' || key === 'bottom') {
			const { list } = get()
			const result = listOrderClick(list, key)
			set({
				list: result,
			})
			changeCalleeList()
		}
	},
	resetSearchInput: () => {
		set({ inputKeyUp: '' })
	},
	saveStartList: () => {
		const { list } = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const params: Mt[] = []
		list.forEach((item) => {
			params.push(item.mcc)
		})
		fetchRollCallCallee(meetingMoid, 0, params)
	},
	isMeetingVoiceInspireOn: () => {
		const mccInfo = useMccStore.getState().mccInfo
		let voiceInspireState = mccInfo.voiceInspireState
		return voiceInspireState === 1
	},
	getMtByMtid: (mtid: string) => {
		const tableAll = useTableAllStore.getState().tree
		if (mtid) {
			let mtInfo: MccModel<IMcc> | null = getItemByMtKey(tableAll, mtid)
			if (mtInfo !== null && mtInfo.mcc.isMt) {
				return revert_mt(mtInfo.mcc)
			}
		}
		return null
	},
	isMtOnline: (mt) => {
		const { getMtByMtid } = get()
		let lmt = getMtByMtid(mt.mt_key ?? '')
		if (lmt == null) {
			if (mt.online === 1) {
				return true
			}
			return false
		} else {
			if (lmt.online === 1) {
				return true
			}
		}
		return false
	},
	checkRollAll: async () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchRollCallCheck(meetingMoid)
		const handleChairmanPollStart = () => {
			Confirm(t('管理方轮询已开启，与点名轮询冲突。确定要关闭管理方轮询，开启点名轮询？'), async () => {
				//手动发停止所有轮询请求
				const resStop = await fetchUpdatePollState(meetingMoid, 2, 0)
				if (resStop) {
					get().startPost()
				} else {
					Alert(t('结束失败'))
				}
			})
		}
		const handleMeetingPollStart = () => {
			Confirm(t('会议轮询已开启，与点名轮询冲突。确定要关闭会议轮询，开启点名轮询？'), async () => {
				//手动发停止所有轮询请求
				const resStop = await fetchUpdatePollState(meetingMoid, 1, 0)
				if (resStop) {
					get().startPost()
				} else {
					Alert(t('结束失败'))
				}
			})
		}
		const handleStopAllPoll = () => {
			Confirm(t('轮询已开启，与点名轮询冲突。确定要关闭轮询，开启点名轮询？'), async () => {
				//手动发停止所有轮询请求
				const resStop = await fetchStopRollCall(meetingMoid)
				if (resStop) {
					get().startPost()
				} else {
					Alert(t('结束失败'))
				}
			})
		}
		if (res.success && res.data) {
			if (res.data.poll_is_on && res.data.poll_ma_is_on) {
				handleStopAllPoll()
			} else if (res.data.poll_is_on) {
				handleMeetingPollStart()
			} else if (res.data.poll_ma_is_on) {
				handleChairmanPollStart()
			} else {
				get().startPost()
			}
		}
	},
	startRollcall: () => {
		let result = get().list.map((item) => {
			item.status.pass = 2
			return item
		})
		/**清空上次点名人状态*/
		set({ state: 1, disabledModeSelect: true, disabledPlanSelect: true, list: result })
	},
	_isAllRollcalleesOffline: () => {
		const { list, isMtOnline } = get()
		for (let index = 0, end = list.length; index < end; index++) {
			if (isMtOnline(revert_mt(list[index].mcc))) {
				return false
			}
		}
		return true
	},
	_rollCallTheFirstInList: function (mt) {
		const { getFirstRollcalleeInList, _checkMtCanBeRollcall, rollCallMember, getLiDom, toggleClick, list } = get()
		let _mt: MtEntity | null = mt ?? getFirstRollcalleeInList()
		let _index = getLiDom(_mt?.mt_key ?? '') // 获取终端位置
		let flag = true
		for (let i = _index; i < list.length; i++) {
			let _mt = revert_mt(list[i].mcc)
			if (_mt) {
				let result = _checkMtCanBeRollcall(_mt)
				if (result === 'ok') {
					flag = false
					rollCallMember(_mt, null)
					toggleClick(_mt.mt_key)
					break
				}
			}
		}
		if (flag) {
			throw new Error('')
		}
	},
	setRollcaller: (rollcaller) => {
		let _callerOptions = get().callerOptions
		var isExist = some(_callerOptions, (o) => {
			return o.mtKey === rollcaller?.mt_key
		})
		set({ callerValue: !isExist ? '-1' : rollcaller?.mt_key ?? '-1', cur_roll_caller: rollcaller })
	},
	setRollcallState: () => {
		const { state, startRollcall, stopRollcall } = get()
		state ? startRollcall() : stopRollcall()
	},
	startPostCallback: async () => {
		const {
			startRollcall,
			enableSignResultBtn,
			_rollCallTheFirstInList,
			_isAllRollcalleesOffline,
			getFirstRollcalleeInList,
		} = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		//开启轮询成功后的回调函数
		startRollcall() //渲染页面
		enableSignResultBtn() //禁用签到表
		const resStopSelect = await fetchStopAllSelectView(meetingMoid)
		if (!resStopSelect) {
			Alert(t('取消所有选看失败'))
		}
		if (_isAllRollcalleesOffline()) {
			Alert(t('当前无任何在线与会方，无法进行会议点名'))
			return
		}
		var mt = getFirstRollcalleeInList() //拿到第一个
		try {
			_rollCallTheFirstInList(mt)
		} catch (e) {
			Alert(t('当前没有可以被点名的与会方'))
			return
		}
	},
	startPost: () => {
		const { preName, modeValue, getCurRollCaller, rcShow, startPostCallback } = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const _cur_roll_caller = getCurRollCaller()
		set({ openShow: false })
		useMonitorStore.getState().showRollCallDialog()
		rcShow()
		setTimeout(async () => {
			if (_cur_roll_caller) {
				const res = await fetchStartRollCall(meetingMoid, {
					mode: modeValue,
					name: preName,
					roll_caller: _cur_roll_caller,
				})
				if (res.success) {
					startPostCallback()
				} else {
					// TS.monitor?.dialog.hide()
					useMonitorStore.getState().closeRollCall()
					Alert(res.description || t('操作失败'))
				}
			}
		}, 200)
	},
	pageDataClearCurRollcallee: () => {
		set({ cur_roll_callee: null })
	},
	pageDataGetCurRollcallee: () => {
		return get().cur_roll_callee
	},
	startBtnClick: async () => {
		const { isMeetingVoiceInspireOn, list, callerValue, stopRollcall, checkRollAll, pageDataClearCurRollcallee } =
			get()
		pageDataClearCurRollcallee() //清除缓存
		if (callerValue === '-1' || list.length === 0) {
			//点名人不存在
			Alert(t('请先指定点名人和被点名人，再开启会议点名'))
			return
		}
		if (isMeetingVoiceInspireOn()) {
			stopRollcall()
			Alert(t('会议点名和语音激励不能同时开启'))
			return
		}
		checkRollAll()
	},
	stopRollClick: async () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchStopRoll(meetingMoid)
		if (res.success) {
			get().stopRollcall()
		} else {
			// TS.monitor?.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			Alert(res.description || t('操作失败'))
		}
		// TS.monitor.dialog.hide()
		useMonitorStore.getState().closeRollCall()
	},
	stopRollcall: () => {
		// hideAllPassBtn()
		set({
			state: 0,
			disabledCallPre: true,
			disabledCallNext: true,
			disabledModeSelect: false,
			disabledPlanSelect: false,
		})
	},
	callPre: () => {
		const { closeRemark, disabledCallPre, getRollcallee, cur_roll_callee, setMtSelected, _rollcallMemberSendMess } =
			get()
		closeRemark()
		if (disabledCallPre) {
			console.log('按钮被禁用')
			return
		}
		let preMt = getRollcallee(-1)
		if (!preMt) {
			cur_roll_callee && setMtSelected(cur_roll_callee)
			Alert(t('当前被点名人前面没有可以被点名的与会方'))
			return
		} else {
			setMtSelected(preMt) //渲染页面
			_rollcallMemberSendMess(preMt) //点名终端
		}
	},
	callNext: () => {
		const {
			closeRemark,
			disabledCallNext,
			getRollcallee,
			cur_roll_callee,
			setMtSelected,
			_rollcallMemberSendMess,
		} = get()
		closeRemark()
		if (disabledCallNext) {
			console.log('按钮被禁用')
			return
		}
		let nextMt = getRollcallee(1)
		if (!nextMt) {
			cur_roll_callee && setMtSelected(cur_roll_callee)
			Alert(t('当前被点名人前面没有可以被点名的与会方'))
			return
		} else {
			setMtSelected(nextMt)
			_rollcallMemberSendMess(nextMt)
		}
	},
	sendMess: (rollMode, rollcaller, rollcallee) => {
		const {
			setMtToSpeaker,
			rollcallerSelectViewRollcallee,
			setMtToChairman,
			cancelChairman,
			cur_roll_callee,
			_handleStopOldRollcallerSelect,
			_handleStopOldRollcalleeSelectRollcaller,
			pre_roll_caller,
		} = get()
		const { chairman } = useManagerStore.getState()
		if (rollMode == '2') {
			//点名模式
			//把点名人设置为发言方  先发设置成为发言方的消息
			rollcaller && setMtToSpeaker(rollcaller)
			if (chairman && rollcaller && rollcaller.mt_key === chairman.mtKey) {
				setTimeout(function () {
					rollcallee && rollcaller && rollcallerSelectViewRollcallee(rollcaller, rollcallee)
				}, 250)
			} else {
				setTimeout(function () {
					//把点名人设置成管理方
					rollcaller &&
						setMtToChairman(rollcaller, function () {
							//200里再调用选看，防止选看在主席之前，会造成选看消息无用
							rollcallee && rollcallerSelectViewRollcallee(rollcaller, rollcallee)
						})
				}, 1000)
			}
		} else if (rollMode == '3') {
			//被点名模式
			//判断有管理方，管理方就是点名人不处理；管理方不是点名人，则设置点名人为管理方；无管理方，设置点名人为管理方
			if (rollcaller?.mt_key !== chairman?.mtKey) {
				//把点名人设置成管理方
				rollcaller && setMtToChairman(rollcaller)
			}
			setTimeout(function () {
				//把被点名人设置为发言方  先发设置成为发言方的消息
				rollcallee && setMtToSpeaker(rollcallee)
			}, 1000)
		} else {
			//合成模式
			//把如果有管理方，取消当前管理方
			cancelChairman()
			//把点名人设置为发言方  先发设置成为发言方的消息
			rollcaller &&
				rollcallee &&
				setMtToSpeaker(rollcaller, function () {
					// 被点名人选看点名人（只选看视频）
					rollcallerSelectViewRollcallee(rollcallee, rollcaller, true)
					// 点名人选看被点名人（只选看视频）
					rollcallerSelectViewRollcallee(rollcaller, rollcallee, true)
				})
			setTimeout(function () {
				if (
					cur_roll_callee == null ||
					cur_roll_callee.mt_key == null ||
					cur_roll_callee.mt_key === rollcallee?.mt_key
				) {
					return
				}
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				fetchStopSelectView(meetingMoid, {
					dst_account: cur_roll_callee.mt_id,
					media_mode: 1,
				}).then((res) => {
					if (!res) {
						Alert(t('取消选看失败'))
					}
				})
			}, 1000)
			setTimeout(function () {
				if (
					pre_roll_caller == null ||
					pre_roll_caller.mt_key == null ||
					pre_roll_caller.mt_key === rollcallee?.mt_key ||
					pre_roll_caller.mt_key === rollcaller?.mt_key
				) {
					return
				}
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				fetchStopSelectView(meetingMoid, {
					dst_account: pre_roll_caller.mt_id,
					media_mode: 1,
				}).then((res) => {
					if (!res) {
						Alert(t('取消选看失败'))
					}
				})
			}, 1000)
		}
	},
	_rollcallMemberSendMess: (rollcallee) => {
		const {
			pageDataGetCurRollcallee,
			_handleCheckRollCallEnvironment,
			modeValue,
			getCurRollCaller,
			cancelChairman,
			setMtToChairman,
			_handleChangeMixMember,
			_handleNewRollcalleeIntoMonitor,
			setMtToSpeaker,
			_handleStopOldRollcalleeSelectRollcaller,
			_handleChangeMixMemberBe,
			rollcallerSelectViewRollcallee,
			_handleStopOldRollcallerSelect,
			_getCurChairman,
		} = get()
		let preMt = pageDataGetCurRollcallee() // 上一次的点名终端  当前的终端状态还未切换因此获取当前的被点名人其实是旧的点名人
		const flag = _handleCheckRollCallEnvironment(rollcallee) // 检测当前环境 存在、点名人在线 被点名人可进行被点名
		if (!flag) {
			return
		}
		var rollcaller = getCurRollCaller() // 当前的点名人
		const { speaker, chairman } = useManagerStore.getState()
		const speakerflag = speaker && speaker.mtKey != rollcaller?.mt_key // 点名人已经和发言人不一致 true代表不一致 false 代表一致
		const chairmanflag = chairman && chairman.mtKey != rollcaller?.mt_key // 管理方和点名人不一致 true代表不一致 false 代表一致
		if (modeValue == '2') {
			//点名模式
			// 发言人不必延时设置  主要判断管理方
			if (!chairmanflag && !speakerflag) {
				_handleNewRollcalleeIntoMonitor(rollcallee) // 传入当前点名人  并判断是否要传入下一个点名人 当前图像预览来判断
				// 已设置管理方 已设置发言方 且与当前的点名人一致
				rollcallerSelectViewRollcallee(rollcaller, rollcallee) // 点名人选看新被点名人
				_handleChangeMixMember(rollcallee) // 修改混音成员。
			}
			if (chairmanflag && speakerflag) {
				// 未设置管理方 未设置发言方 且与当前的点名人一致  那么貌似就是初始化
				setMtToSpeaker(rollcaller) // 设置发言方
				setTimeout(function () {
					//把点名人设置成管理方
					rollcaller &&
						setMtToChairman(rollcaller, function () {
							//200里再调用选看，防止选看在主席之前，会造成选看消息无用
							rollcallerSelectViewRollcallee(rollcaller, rollcallee)
						})
				}, 1000)
				setTimeout(function () {
					_handleChangeMixMember(rollcallee) // 修改混音成员。
					_handleNewRollcalleeIntoMonitor(rollcallee) // 传入下一个点名人
				}, 230)
			}
			if (!speakerflag && chairmanflag) {
				// 已设置发言方 未设置管理方 且与当前的点名人一致
				_handleChangeMixMember(rollcallee) //修改混音成员。
				_handleNewRollcalleeIntoMonitor(rollcallee) // 传入下一个点名人
				setTimeout(function () {
					//把点名人设置成管理方 并在回调调用选看
					rollcaller &&
						setMtToChairman(rollcaller, function () {
							//200里再调用选看，防止选看在主席之前，会造成选看消息无用
							rollcallerSelectViewRollcallee(rollcaller, rollcallee) // 设置选看
						})
				}, 1000)
			}
			if (speakerflag && !chairmanflag) {
				// 未设置发言方 设置管理方 且与当前的点名人一致
				setMtToSpeaker(rollcaller) // 设置当前的发言人
				_handleChangeMixMember(rollcallee) //修改混音成员有画面合成会清理画面合成消息。
				_handleNewRollcalleeIntoMonitor(rollcallee) // 传入下一个点名人
				// 设置管理方  但需要在250ms调用选看
				setTimeout(function () {
					rollcallerSelectViewRollcallee(rollcaller, rollcallee) // 设置选看
				}, 250)
			}
		}
		if (modeValue == '3') {
			//被点名人模式
			var cMt = _getCurChairman()
			if (cMt && cMt.mt_key != rollcaller?.mt_key) {
				//把点名人设置成管理方
				rollcaller && setMtToChairman(rollcaller)
			}
			//把被点名人设置为发言方  先发设置成为发言方的消息
			_handleChangeMixMemberBe(rollcallee) // 修改混音成员。
			_handleNewRollcalleeIntoMonitor(rollcallee) // 传入下一个点名人
		}
		if (modeValue != '2' && modeValue != '3') {
			//点名模式
			// 1 把如果有管理方，取消当前管理方
			cancelChairman()
			// 2 把点名人设置为发言方  先发设置成为发言方的消息，需要判断点名人和发言人是否一致一致
			if (!speakerflag) {
				// 一致  无设置发言人消息
				// 被点名人选看点名人（只选看视频）1
				rollcaller && rollcallerSelectViewRollcallee(rollcallee, rollcaller, true)
				// 点名人选看被点名人（只选看视频）2
				rollcallerSelectViewRollcallee(rollcaller, rollcallee, true)
				// 新点名人进入监控 3
				_handleNewRollcalleeIntoMonitor(rollcallee)
				// 修改合成人员修改混音成员混音成员（过程主要依靠后台执行）
				_handleChangeMixMember(rollcallee) // 修改合成人员修改混音成员混音成员。
				// 停止旧被点名人
				preMt && _handleStopOldRollcalleeSelectRollcaller(preMt, rollcallee)
				// 停止旧点名人选看
				setTimeout(() => {
					_handleStopOldRollcallerSelect(rollcallee)
				}, 1000)
			} else {
				// 不一致  需要在设置发言人的回调里面去执行 sendMess 里面的发言人设置互相选看  需要在设置反烟人之后
				setMtToSpeaker(rollcaller, function () {
					// 被点名人选看点名人（只选看视频）1
					rollcaller && rollcallerSelectViewRollcallee(rollcallee, rollcaller, true)
					// 点名人选看被点名人（只选看视频）2
					rollcallerSelectViewRollcallee(rollcaller, rollcallee, true)
					// 新点名人进入监控 3
					_handleNewRollcalleeIntoMonitor(rollcallee)
					// 修改合成人员修改混音成员混音成员（过程主要依靠后台执行） 4/5
					_handleChangeMixMember(rollcallee) // 修改合成人员修改混音成员混音成员。
					// 停止旧被点名人选看点  6  停止上一轮选看
					preMt && _handleStopOldRollcalleeSelectRollcaller(preMt, rollcallee)
					// 停止旧点名人选看点  6  停止上一轮选看
					setTimeout(() => {
						_handleStopOldRollcallerSelect(rollcallee)
					}, 1000)
				})
			}
		}
	},
	_handleStopOldRollcallerSelect: (rollcallee) => {
		const { getCurRollCaller, pre_roll_caller } = get()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let rollcaller = getCurRollCaller()
		if (
			pre_roll_caller == undefined ||
			pre_roll_caller.mt_key == null ||
			pre_roll_caller.mt_key == rollcallee.mt_key ||
			pre_roll_caller.mt_key == rollcaller?.mt_key
		) {
			return
		}
		fetchStopSelectView(meetingMoid, {
			dst_account: pre_roll_caller.mt_id,
			media_mode: 1,
		}).then((res) => {
			if (!res) {
				Alert(t('取消选看失败'))
			}
		})
	},
	// 停止旧被点名人选看点名人(画面合成)
	_handleStopOldRollcalleeSelectRollcaller: (preMt, rollcallee) => {
		if (preMt == null || preMt.mt_key == null || preMt.mt_key == rollcallee.mt_key) {
			return
		}
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		fetchStopSelectView(meetingMoid, {
			dst_account: preMt.mt_id,
			media_mode: 1,
		}).then((res) => {
			if (!res) {
				Alert(t('取消选看失败'))
			}
		})
	},
	_handleChangeMixMember: function (rollcallee) {
		const { modeValue, getCurRollCaller, _handleDealSetRoll, setRollcallResult } = get()
		let cur_roll_caller = getCurRollCaller()
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		if (cur_roll_caller) {
			fetchRollCaller(meetingMoid, {
				mode: Number(modeValue),
				roll_callee: rollcallee,
				roll_caller: cur_roll_caller,
			}).then((res: any) => {
				if (res.success) {
					_handleDealSetRoll(rollcallee)
				} else {
					if (res.data == 'ROLLCALL_MIX_FAIL') {
						//定制混音失败
						setRollcallResult(rollcallee.mt_key, 0)
						//直接把点名设置成点名失败
						Alert(t('点名失败（无法开启定制混音）'))
					} else {
						var msg = res.description || t('操作失败')
						Alert(msg)
					}
				}
			})
		}
	},
	_handleChangeMixMemberBe: (rollcallee) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { modeValue, getCurRollCaller, _handleDealSetRoll, setRollcallResult, setMtToSpeaker } = get()
		let cur_roll_caller = getCurRollCaller()
		if (cur_roll_caller) {
			fetchRollCaller(meetingMoid, {
				mode: Number(modeValue),
				roll_callee: rollcallee,
				roll_caller: cur_roll_caller,
			}).then((res: any) => {
				if (res.success) {
					setMtToSpeaker(rollcallee) // 设置当前的发言方
					_handleDealSetRoll(rollcallee)
				} else {
					if (res.data == 'ROLLCALL_MIX_FAIL') {
						//定制混音失败
						setRollcallResult(rollcallee.mt_key, 0)
						//直接把点名设置成点名失败
						Alert(t('点名失败（无法开启定制混音）'))
					} else {
						var msg = res.description || t('操作失败')
						Alert(msg)
					}
				}
			})
		}
	},
	// 处理改变混音成员的回调
	_handleDealSetRoll: function (rollcallee) {
		get().setMtSelected(rollcallee)
		get().enableSignResultBtn() //启用签到表按钮
	},
	// 传递控件下一次点名人消息
	_handleNewRollcalleeIntoMonitor: function (rollcallee) {
		const { setCurRollcallee, state, getRollcallee } = get()
		setCurRollcallee(rollcallee)
		let nextcurCallee = getRollcallee(1, true)
		console.timeEnd(t('开始调用'))
		if (!state) {
			// TS.monitor.dialog.show()
			useMonitorStore.getState().showRollCallDialog()
		} else {
			if (nextcurCallee) {
				// TS.monitor.dialog.show(rollcallee, nextcurCallee)
				useMonitorStore.getState().showRollCallDialog(rollcallee, nextcurCallee)
			} else {
				// TS.monitor.dialog.show(rollcallee, null)
				useMonitorStore.getState().showRollCallDialog(rollcallee)
			}
		}
		set({ openShow: true })
	},
	rcShow: () => {
		const { cur_roll_callee, getRollcallee, state, openShow } = get()
		let nextcurCallee = getRollcallee(1, true)
		if (openShow) {
			//关闭远摇
			// TS.monitor.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			set({ openShow: false })
		} else {
			//开启远摇
			if (!useMonitorStore.getState().appCheckHasReadyAndStart()) {
				return
			}
			if (useMonitorStore.getState().NeedMustUpdateExeVersion) {
				useMonitorStore.getState().showUpdateDialog()
				return
			}
			if (!state) {
				// TS.monitor.dialog.show()
				useMonitorStore.getState().showRollCallDialog()
			} else {
				if (nextcurCallee) {
					// TS.monitor.dialog.show(cur_roll_callee, nextcurCallee)
					useMonitorStore.getState().showRollCallDialog(cur_roll_callee ?? undefined, nextcurCallee)
				} else {
					if (cur_roll_callee) {
						// TS.monitor.dialog.show(cur_roll_callee, null)
						useMonitorStore.getState().showRollCallDialog(cur_roll_callee)
					} else {
						// TS.monitor.dialog.show(null, null)
						useMonitorStore.getState().showRollCallDialog()
					}
				}
			}
			set({ openShow: true })
		}
	},
	showSignResult: () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const mt_portrait_type = useGlobalStore.getState().user?.personal_config.mt_portrait_type
		window.open(
			MEETING_JUMP_URL + `/mcc/showSignResult?meetingMoid=${meetingMoid}&personalConfig=${mt_portrait_type}`
		)
	},
	isRollcallCurrent: () => {
		if (get().state) {
			return true
		}
		return false
	},
	checkMtCanBeRollCall: (cur_roll_callee: MtEntity) => {
		const { getCurRollCaller } = get()
		const rollCallerInfo = getCurRollCaller() /**获取当前点名人 */
		// 没有点名人
		if (!rollCallerInfo) {
			return t('请设置点名人')
		}
		// 点名人不在线
		if (!rollCallerInfo || rollCallerInfo.online !== 1) {
			return t('点名人不在线')
		}
		// 检测点名人和被点名人
		if (rollCallerInfo.mt_key === cur_roll_callee.mt_key) {
			return t('点名人和被点名人不能为同一个人')
		}
		// 被点名终端不在线时
		if (!cur_roll_callee.online) {
			return t('被点名人不在线')
		}
		return 'ok'
	},
	addMtToRollcallerSelectList: (mt) => {
		const { callerOptions: result } = get()
		if (mt.conf_level != 2) {
			return false
		}
		result.push({ mtKey: mt.mt_key, name: mt.name })
		set({ callerOptions: result })
	},
	addMtToCalleeList: (mt) => {
		const { addMtFlag, isSearch, searchCacheMt, thisMts, resetSearch, doSearch, changeCalleeList, list } = get()
		let _searchCacheMt = []
		let _list = []
		if (addMtFlag /**点名轮询时添加终端 */) {
			var cMts = thisMts
			for (var i = 0, lng = cMts.length; i < lng; i++) {
				var cMt = cMts[i]
				if (null === cMt) {
					continue
				}
				//别名加ip的cMt.account 不等于 mt.account
				if (
					cMt.mt_key == mt.mt_key ||
					cMt.account == mt.account ||
					cMt.account == mt.moid ||
					(cMt.mt_type == 8 && new RegExp('@' + mt.account + '$').test(cMt.account))
				) {
					if (isSearch) {
						_searchCacheMt.push(mt)
						resetSearch()
						doSearch('')
						set({ searchCacheMt: [...searchCacheMt, ..._searchCacheMt] })
					} else if (searchCacheMt.length) {
						_searchCacheMt.push(mt)
						set({ searchCacheMt: [...searchCacheMt, ..._searchCacheMt] })
					} else {
						_list.push(ListTranslator([mt]))
						let result = list.filter((item) => {
							return !(item.mtKey === mt.mt_key || item.mcc.account === mt.account)
						})
						set({ list: [...result, ..._list[0]] })
						changeCalleeList()
					}
				}
			}
			cMts = cMts.filter((item) => item != null)
			if (cMts.length === 0) {
				set({ addMtFlag: false })
			}
		}
	},
	mtOnlineStatusChangeNotify: (onlineMts, offlineMts, newAddMts, isDel) => {
		const {
			isRollcallCurrent,
			addMtToRollcallerSelectList,
			callerOptions,
			callerValue,
			addMtToCalleeList,
			markOfflineMtInRollcallerList,
			getCurRollCaller,
		} = get()
		if (isDel) {
			if (!isRollcallCurrent()) {
				let result = callerOptions.filter((item) => {
					return item.mtKey != offlineMts[0].mt_key
				})
				set({ callerOptions: result })
				if (offlineMts[0].mt_key == callerValue) {
					//下线的终端刚好是点名人
					set({ callerValue: '-1' })
				}
				return
			}
		}
		if (!isRollcallCurrent()) {
			return
		}
		//上线的终端（包括新增的且上线的终端）
		onlineMts.forEach(function (mt) {
			addMtToRollcallerSelectList(mt) //把上线的终端添加到点名人select下拉列表中
		})
		onlineMts.forEach(addMtToCalleeList)
		//下线的终端
		offlineMts.forEach(function (mt) {
			var mtKey = mt.mt_key
			markOfflineMtInRollcallerList(mt) //在点名人select下拉列表中标记下线的终端
			if (getCurRollCaller() && mtKey == getCurRollCaller()?.mt_key) {
				//下线的终端刚好是点名人
				Alert(t('当前点名人已离线。'))
				set({ callerValue: '-1' })
			} else if (mtKey == callerValue) {
				Alert(t('当前点名人已离线。'))
				set({ callerValue: '-1' })
			}
		})
		newAddMts.forEach(addMtToCalleeList)
	},
	getLiDom: (key: string) => {
		let index = get().list.findIndex((item) => key === item.mtKey)
		return index
	},
	getRollcallee: (upOrDown, isCheck) => {
		const { moveThroughList, checkMtCanBeRollCall, pageGetCurRollcallee, getLiDom, list, cur_roll_callee } = get()
		/**
		 * 判断一下当前点名人位置
		 * 如果当前点名人已经是在最后一个并且当前继续向下寻找  直接返回null
		 * 如果当前点名人已经是在第一个并且当前继续向上寻找  直接返回null
		 * */
		if (cur_roll_callee && cur_roll_callee.mt_key) {
			let _index = getLiDom(cur_roll_callee?.mt_key ?? '')
			if (_index === list.length - 1 && upOrDown === 1) {
				return null
			}
			if (_index === 0 && upOrDown === -1) {
				return null
			}
		}
		let mt = null
		let result = ''
		let curMt = moveThroughList(upOrDown, mt, !!isCheck) /**获取移动后的终端*/
		let _index = getLiDom(curMt?.mt_key ?? '') /**获取终端位置 */
		let _mt = null
		if (_index === -1) {
			return null
		}
		if (upOrDown === 1) {
			/**从此位置遍历  找寻满足条件终端*/
			for (let i = _index; i < list.length; i++) {
				let curMt = revert_mt(list[i].mcc)
				if (curMt && curMt.mt_key != null) {
					mt = curMt
				} else {
					mt = pageGetCurRollcallee()
				}
				if (undefined == mt || mt?.mt_key == null) {
					throw new Error('mtid is undefined')
				}
				result = checkMtCanBeRollCall(mt)
				if (result === 'ok') {
					_mt = mt
					break
				}
			}
		} else {
			/**从此位置遍历  找寻满足条件终端*/
			for (let i = _index; i >= 0; i--) {
				let curMt = revert_mt(list[i].mcc)
				if (curMt && curMt.mt_key != null) {
					mt = curMt
				} else {
					mt = pageGetCurRollcallee()
				}
				if (undefined == mt || mt?.mt_key == null) {
					throw new Error('mtid is undefined')
				}
				result = checkMtCanBeRollCall(mt)
				if (result === 'ok') {
					_mt = mt
					break
				}
			}
		}
		return _mt
	},
	removeClick: (mt) => {
		get().delRollCall([mt])
	},
	delMt: (mt) => {
		get().delRollcallee(mt)
	},
	delRollcallee: (mt) => {
		if (useMccStore.getState().curPage === 'rollcall') {
			let unCheckedList = get().list.filter((x) => mt.mt_key !== x.mtKey)
			set({ list: unCheckedList })
		}
	},
	markOfflineMtInRollcallerList: (mt) => {
		let _callerOptions = get().callerOptions
		let result = filter(_callerOptions, function (o) {
			return o.mtKey !== mt.mt_key
		})
		set({ callerOptions: result })
	},
	hasRollcallees: () => {
		return get().list.length > 0
	},
	moveThroughList: (upOrDown: number, curMt?: MtEntity | null, isCheck?: boolean) => {
		const { list, cur_roll_callee, getLiDom, toggleClick } = get()
		let _cur_roll_callee = curMt || cur_roll_callee /**当前被点名人 */
		let _index = getLiDom(_cur_roll_callee?.mt_key || '')
		if (1 === upOrDown /**向下移动 */) {
			let $next_roll_callee = list[_index + 1] /**下一个点名人*/
			if ($next_roll_callee) {
				if (!isCheck) {
					toggleClick(list[_index + 1].mtKey || '')
				}
				return revert_mt($next_roll_callee.mcc)
			} else {
				return null
			}
		} else if (-1 === upOrDown /**向上寻找*/) {
			let $prev_roll_callee = list[_index - 1] /**上一个点名人*/
			if ($prev_roll_callee) {
				if (!isCheck) {
					toggleClick(list[_index - 1].mtKey || '')
				}
				return revert_mt($prev_roll_callee.mcc)
			} else {
				return null
			}
		}
		return null
	},
	setMtSelected: (mt) => {
		const { list, checkLimits, toggleClick } = get()
		/**获取第一个被选中的*/
		let result = list.find((item) => {
			return item.status.checked
		})
		if (result?.mtKey === mt?.mt_key) {
			toggleClick(mt?.mt_key ?? '')
			checkLimits()
			return
		} else {
			toggleClick(mt?.mt_key ?? '')
			checkLimits()
		}
	},
	searchInputKeyup: (val: string) => {
		set({ inputKeyUp: val })
		setTimeout(function () {
			get().doSearch(val)
		}, 400)
	},
	doSearch: (key: string) => {
		const { searchSuccessCall, getSearchResult } = get()
		if (key === '') {
			set({ isSearch: false })
		}
		if (key !== '') {
			set({ isSearch: true })
		}
		getSearchResult(key, searchSuccessCall)
	},
	getSearchResult: async (text, successCallbackFn: (params: searchSuccessCallParamsEntity) => void) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchSearchCallee(meetingMoid, { key: text })
		if (res.success) {
			const { roll_callee_no_pass = [], roll_callee_pass = [], roll_callee = [] } = res.data || {}
			successCallbackFn({
				roll_callee_no_pass: roll_callee_no_pass,
				roll_callee_pass: roll_callee_pass,
				roll_callee: roll_callee,
			})
		} else {
			useMonitorStore.getState().closeRollCall()
			Alert(res.description ?? t('操作失败'))
		}
	},
	searchSuccessCall: (_data: searchSuccessCallParamsEntity) => {
		const { searchCacheMt, cur_roll_callee, setMtSelected, renderRollCalleeList, addUserState } = get()
		set({ list: [] })
		let mts = _data.roll_callee
		if (searchCacheMt.length) {
			let flag = true
			for (let i = 0; i < searchCacheMt.length; i++) {
				for (var j = 0; j < mts.length; j++) {
					if (searchCacheMt[i].mt_key === mts[j].mt_key) {
						flag = false
						break
					}
				}
				if (flag) mts.push(searchCacheMt[i])
			}
		}
		set({
			searchCacheMt: [],
			roll_callee_no_pass: _data.roll_callee_no_pass,
			roll_callee_pass: _data.roll_callee_pass,
		})
		if (mts.length > 0) {
			renderRollCalleeList(mts)
			addUserState()
		}
		cur_roll_callee && setMtSelected(cur_roll_callee)
	},
	sendAddMtsAjax(mts) {
		const { addMtsIndrop, searchSuccessCall } = get()
		const result = mts.map((mt) => revert_mt(mt))
		addMtsIndrop(result, searchSuccessCall)
	},
	dropMtInSearch: function (mts) {
		const { resetSearch, getSearchResult, searchSuccessCall, sendAddMtsAjax } = get()
		if (!mts || mts.length == 0) return
		resetSearch()
		getSearchResult('', (data) => {
			searchSuccessCall(data)
			let userMtKeys = (data.roll_callee || []).map((x) => x.mt_key)
			let result = []
			for (const paraMt of mts) {
				if (!userMtKeys.includes(paraMt.mtKey)) {
					result.push(paraMt)
				}
			}
			if (result.length > 0) {
				//发送请求添加人员 并返回新的人员列表
				//渲染列表
				sendAddMtsAjax(result)
			}
		})
	},
	/**重置搜索相关内容*/
	resetSearch: () => {
		set({ disabledClear: false, isSearch: false, inputKeyUp: '' })
	},
	/**渲染被选看列表 */
	renderRollCalleeList: (mts: Array<MtEntity>) => {
		if (mts.length > 0) {
			if (mts.length > 5000) {
				Alert(t('参与点名与会方最多为5000方'))
				return
			}
			set({
				list: ListTranslator(mts || []),
			})
			get().enableSignResultBtn()
		}
	},
	/**为被点名人添加点名状态 更改List状态 */
	addUserState: () => {
		const { getStatePass, list: callee, roll_callee_pass, roll_callee_no_pass } = get()
		if (callee.length > 0) {
			callee.forEach((mt) => {
				/**获取点名状态*/
				var rollcalleeState = getStatePass(mt.mtKey, roll_callee_pass, roll_callee_no_pass)
				mt.status.pass = rollcalleeState
			})
		}
		set({ list: [...callee] })
	},
	getStatePass: (mtKey: string, calleePass: Array<MtEntity>, calleeNoPass: Array<MtEntity>): number => {
		for (var key in calleePass) {
			//点名通过的被点名人
			let mt = calleePass[key]
			if (mtKey === mt.mt_key) {
				return 1
			}
		}
		for (let key in calleeNoPass) {
			//点名通过的被点名人
			let mt = calleeNoPass[key]
			if (mtKey === mt.mt_key) {
				return 0
			}
		}
		return 2
	},
	addMtsIndrop: async (mts, successCallbackFn) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchAddRollCallCallee(meetingMoid, mts)
		if (res.success) {
			const { roll_callee_no_pass = [], roll_callee_pass = [], roll_callee = [] } = res.data || {}
			successCallbackFn({
				roll_callee_no_pass: roll_callee_no_pass,
				roll_callee_pass: roll_callee_pass,
				roll_callee: roll_callee,
			})
		} else {
			Alert(res.description ?? t('操作失败'))
		}
	},
	rollcallerSelectViewRollcallee: async (dstAccount, srcAccount, Bus) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let params: SelectViewParamsEntity = {
			src_account: srcAccount?.mt_id ?? '',
			dst_account: dstAccount?.mt_id ?? '',
			flag: 1,
			media_mode: 1,
		}
		if (Bus && useMccStore.getState().mccInfo.meetingType != 1) {
			//合成模式且非端口会议
			params.use_media = 1
		}
		fetchStartSelectView(meetingMoid, params)
	},
	initPollSchema: async (planName) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const res = await fetchGetRollPlanList(meetingMoid)
		if (res.success && res.data) {
			const planData = res.data
			let arr = planData ? planData.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			set({ planOptions: arr })
			/**新增预案,更新预案(刷新预案列表)*/
			planName && set({ preName: planName })
		} else {
			// TS.monitor.dialog.hide()
			useMonitorStore.getState().closeRollCall()
			Alert(t('获取预案失败'))
		}
	},
}))
export const useRollCallStore = create(store)
